import {equals, queryURLParams, valueOrDefault} from "jsmethod-extra";
import {SystemConstants} from "./SystemConstants";

/**
 * @author lihh
 * @description 表示 共同的方法
 */
export class CommonUtils {
  /**
   * @author lihh
   * @description 构建 url params 的方法
   * @param url 访问的url
   */
  public static buildURLSearchParams(url: string): Record<string, string> {
    return queryURLParams(
      valueOrDefault(url, SystemConstants.EmptyString)
    );
  }

  /**
   * @author lihh
   * @description 拿到 client id
   * @param fetchEvent
   */
  public static getClientID(fetchEvent: FetchEvent) {
    return fetchEvent.resultingClientId || fetchEvent.clientId;
  }

  /**
   * @author lihh
   * @description 表示 get 请求
   * @param request 请求体
   */
  public static isNotGet(request: Request): boolean {
    return !equals(request.method.toUpperCase(), "GET");
  }

  /**
   * @author lihh
   * @description 读取 html 流
   * @param response 响应
   */
  public static async readHTMLStream(response: Response): Promise<string> {
    const cloneResponse = response.clone();

    // 获取 ReadableStream
    const reader = cloneResponse.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let htmlText = "";

    // 读取流
    while (true) {
      const { done, value } = await reader.read();

      // 如果读取完成，退出循环
      if (done) break;

      // 将 Uint8Array 转换为字符串并追加到 htmlText
      htmlText += decoder.decode(value, { stream: true });
    }

    return htmlText;
  }
}
